package com.mycloud.dictionary.service;

import com.mycloud.core.service.GenericServiceImpl;
import com.mycloud.dictionary.dao.DictionaryDao;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 12/14/11
 * Time: 4:10 PM
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CloudDictionaryService extends GenericServiceImpl<DictionaryDao> implements DictionaryService {

    private HttpClient httpClient;

    public String getFarsi123Translation(String word) throws Exception {

        if(httpClient == null){
            httpClient = new DefaultHttpClient();
        }

        HttpGet httpGet = new HttpGet("http://www.farsi123.com/?word=" + word);
        HttpResponse httpResponse = httpClient.execute(httpGet);

        StringWriter writer = new StringWriter();
        IOUtils.copy(httpResponse.getEntity().getContent(), writer, "UTF-8");
        String response = writer.toString();

        return response;
    }


    public void downloadAudio(String audioPath) throws IOException {
        if(httpClient == null){
            httpClient = new DefaultHttpClient();
        }

        HttpGet httpGet = new HttpGet("http://www.farsi123.com/audio_files/" + audioPath);
        HttpResponse httpResponse = httpClient.execute(httpGet);

        String apath = audioPath.replace("/", "\\");
        String file = "C:\\downloads\\audio\\" + apath;
        String dir = file.substring(0, file.lastIndexOf("\\"));
        File fileDir = new File(dir);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }

        httpResponse.getEntity().writeTo(new FileOutputStream(file));
    }

    @Transactional("wordcloud")
    public void setAudioPath(String word, String audioPath) {
       dao.setAudioPath(word, audioPath);
    }


    @Transactional("wordcloud")
    public void persist(String word, String translation) {
        dao.persist(word, translation);
    }

    public List<String> getAllWords() {
        return dao.getAll();
    }

    public List<String> getAllWordsNotHavingAudioPath() {
        return dao.getAllWordsWordsNotHavingAudioPath();
    }

    public String getDatabaseTranslation(String word) {
        return dao.getDatabaseTranslation(word);
    }


    @Autowired
    public void setDao(DictionaryDao dictionaryDao) {
        this.dao = dictionaryDao;
    }

}
